package site.zhangzhuo.JPA;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
public class TestRestController {

    @Autowired
    private StudentRepository studentRepository;
    @GetMapping("/student")
    public Object getStudent(@RequestParam String id){
        Optional<Student> opt = studentRepository.findById(id);
        //存在返回的Student对象
        if(opt.isPresent()){
            return opt.get();
        }
        //不存在返回null
        return null;
    }

    @PostMapping("/student")
    public String addStudent(@RequestParam String id, @RequestParam String name){
        studentRepository.save(new Student(id,name));
        return "ok";
    }

    @PutMapping("/student")
    public String updateStudent(@RequestParam String id, @RequestParam String name){
        studentRepository.save(new Student(id,name));
        return "ok";
    }

    @DeleteMapping("/student")
    public String deleteStudent(@RequestParam String id){
        studentRepository.deleteById(id);
        return "ok";
    }

    @PostMapping("/validation")
    public String validation(@Validated @RequestBody Student request, BindingResult results) {
        //把实体注解中的错误信息返回
        if (results.hasErrors()) {
            return results.getFieldError().getDefaultMessage();
        }
        return "ok";
    }
}